package loginbean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ManageObjects
{
	private Connection conn = null;
	
	public ManageObjects()
	{
		try 
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","");
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}

	}
	public boolean deleteObject(int objectId)
	{
		Statement st;
		try {
			String strQuery = "delete from fieldtable where objectid=" + objectId;
			st = conn.createStatement();
			st.execute(strQuery);
			strQuery = "delete from objecttable where objectid=" + objectId;
			st = conn.createStatement();
			st.execute(strQuery);
			conn.close();
			return true;
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			return false;
		}		
	}
	public void editObject(int objectId, String newObjectName)
	{
		String strQuery = "update objecttable set objectname='"+ newObjectName +"' where objectid="+ objectId;
		try {
			Statement st = conn.createStatement();
			st.execute(strQuery);
			
			conn.close();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	public void deleteField(int fieldId)
	{
		String strQuery = "delete from fieldtable where fieldid=" + fieldId;
		try {
			Statement st = conn.createStatement();
			st.execute(strQuery);
			
			conn.close();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	public void editField(int fieldId, String newFieldName, String newFieldType)
	{
		String strQuery = null;
		if(newFieldName.length() == 0)
			strQuery = "update fieldtable set datatype='"+ newFieldType +"' where fieldid="+ fieldId;
		else if(newFieldType.length() == 0)
			strQuery = "update fieldtable set fieldname='"+ newFieldName +"' where fieldid="+ fieldId;
		try {
			Statement st = conn.createStatement();
			st.execute(strQuery);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	public void closeDb()
	{
		try 
		{
			conn.close();
		} 
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}
}
